package com.obixlabs.security.credentialsstore.model;

import java.io.Serializable;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class GroupPermissions implements Serializable
{
	private static final long serialVersionUID = 3229927523609087200L;
	
	private Set<ObixPermission> revokedPermissions;
	private Set<ObixPermission> newlyAssignedPermissions;
	private ObixPermissions currentPermissions;
	
	protected GroupPermissions()
	{
		revokedPermissions = new HashSet<ObixPermission>();
		newlyAssignedPermissions = new HashSet<ObixPermission>();
		currentPermissions = new ObixPermissions();		
	}
	
	public GroupPermissions(ObixPermissions permissions)
	{
		this();		
		currentPermissions.putAll(permissions);
	}
	
	public Set<ObixPermission> getRevokedPermissions() 
	{return Collections.unmodifiableSet(revokedPermissions);}
	
	public Set<ObixPermission> getNewlyAssignedPermissions() 
	{return Collections.unmodifiableSet(newlyAssignedPermissions);}
	
	public Map<String, ObixPermission> getCurrentPermissions() 
	{return Collections.unmodifiableMap(currentPermissions);}

	public boolean assignPermission(ObixPermission permission) 
	{
		boolean result = true;
		if (!currentPermissions.containsKey(permission.getName()))
			newlyAssignedPermissions.add(permission);
		else result = false;
		return result;
	}

	public boolean revokePermission(ObixPermission permission) 
	{
		boolean result = true;
		if (currentPermissions.containsKey(permission.getName()))
			revokedPermissions.add(permission);
		else result = false;
		return result;
	}
	
	public boolean isChanged() 
	{
		boolean result;
		if (!newlyAssignedPermissions.isEmpty() || !revokedPermissions.isEmpty())
			result = true;
		else result = false;
		return result;
	}

	@Override
	public boolean equals(Object obj)
	{
		if (this == obj) return true;
		if (obj == null) return false;
		if (!(obj instanceof GroupPermissions)) return false;

		GroupPermissions other = (GroupPermissions) obj;

		if (currentPermissions == null) {
			if (other.currentPermissions != null) return false;
		} else if (!currentPermissions.equals(other.currentPermissions))
			return false;
		
		if (newlyAssignedPermissions == null) {
			if (other.newlyAssignedPermissions != null) return false;
		} else if (!newlyAssignedPermissions
				.equals(other.newlyAssignedPermissions)) return false;
		
		if (revokedPermissions == null) {
			if (other.revokedPermissions != null) return false;
		} else if (!revokedPermissions.equals(other.revokedPermissions))
			return false;
		
		return true;
	}		
}
